﻿#if UNITY_IOS || UNITY_IPHONE

using System.IO;
using HK.Editor.BuildSystem;
using HK.Editor.Common;
using HK.Editor.Utils;
using UnityEditor;
using UnityEngine;

namespace HK.iOS.Editor.BuildSystem
{
    /// <summary>
    /// 工程打包
    /// </summary>
    public static class ProjectBuild
    {
        
#if UNITY_IOS
        
#if COMMAND_MENU
        /// <summary>
        /// 导出XCode工程文件
        /// </summary>
        [MenuItem(EditorConst.MENU_TXT_TOOL_EXPORT_XCOE, false, EditorConst.MENU_PRIORITY_EXPORT_XCOE)]
#endif
        public static void ExportXCodeProject() => ExportXCodeProjectByDir();

        /// <summary>
        /// 导出XCode工程
        /// </summary>
        /// <param name="iOutputDir">导出目录</param>
        public static void ExportXCodeProjectByDir(string iOutputDir = null)
        {
            // 应用参数
            BuildParameters.Apply();
            
            // 输出目录
            var outputDirTmp = iOutputDir;
            if (string.IsNullOrEmpty(outputDirTmp))
            {
                outputDirTmp = BuildParameters.OutputDir;   
            }
            if (string.IsNullOrEmpty(outputDirTmp))
            {
                outputDirTmp = $"{Application.dataPath}/../Output";
            }

            if (!string.IsNullOrEmpty(outputDirTmp) && !Directory.Exists(outputDirTmp))
            {
                Directory.CreateDirectory(outputDirTmp);
            }
            
            var outputDir = $"{outputDirTmp}/XCodePro";
            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }
            
            // TODO:命令行参数设定
            
            // 导出XCode工程
            var report = BuildPipeline.BuildPlayer(
                UtilsBuild.GetAllBuildScenes(), outputDir, 
                BuildTarget.iOS, BuildOptions.None);
            
            // 输出当前App信息
            var buildInfo = UtilsBuild.GenerateAppFileName(BuildTarget.iOS);
            
            var ipaOutputDir = $"{outputDirTmp}/Ipa";
            if (!Directory.Exists(ipaOutputDir))
            {
                Directory.CreateDirectory(ipaOutputDir);
            }
            OutputBuildInfo(ipaOutputDir, buildInfo);
            
            // 打包
            if (0 > report.summary.totalErrors)
            {
                Debug.LogErrorFormat("XCode工程导出失败!(Error:{0})",
                    report.summary);
                UtilsBuild.OutputDebugInfo(outputDirTmp, $"Error:{report.summary}");
            }
        }
        
        /// <summary>
        /// 输出打包信息
        /// </summary>
        /// <param name="iOutputDir">输出目录.</param>
        /// <param name="iBuildInfo">打包信息(如：[BuildId]:[ProductName]).</param>
        private static void OutputBuildInfo(string iOutputDir, string iBuildInfo) 
        {
            var filePath = $"{iOutputDir}/BuildInfo";
            if (File.Exists (filePath)) {
                File.Delete (filePath);
            }

            using (var fStream = new FileStream (filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                // 获得字节数组
                var data = System.Text.Encoding.UTF8.GetBytes(iBuildInfo); 
                // 写入
                fStream.Write (data, 0, data.Length);
            }

        }
        
#endif

    }
}

#endif
